package com.jzo2o.customer.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.*;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageHelperUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
@Slf4j
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Resource
    private AddressBookMapper addressBookMapper;

    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if (CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }

    /**
     * 新增地址
     *
     * @param dto
     * @author afei
     */

    @Override
    public void add(AddressBookUpsertReqDTO dto) {

        AddressBook addressBook = BeanUtils.toBean(dto, AddressBook.class);
        if (BeanUtils.isNotEmpty(dto.getLocation())) {
            String[] split = dto.getLocation().split(",");
            addressBook.setLon(Double.valueOf(split[0]));
            addressBook.setLat(Double.valueOf(split[1]));
        } else {
            addressBook.setLon(null);
            addressBook.setLat(null);
        }
        addressBook.setUserId(UserContext.currentUser().getId());
        Integer count = lambdaQuery().eq(AddressBook::getIsDefault, 1)
                .eq(AddressBook::getUserId, UserContext.currentUserId())
                .count();
        if (count == 0 ) {
            save(addressBook);
        }else {
            addressBook.setIsDefault(0);
            save(addressBook);
        }
    }

    /**
     * 地址簿分页查询
     *
     * @param addressBookPageQueryReqDTO
     * @return
     * @author afei
     */
    @Override
    public PageResult<AddressBook> pageAddressBook(AddressBookPageQueryReqDTO addressBookPageQueryReqDTO) {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<AddressBook> bookLambdaQueryWrapper = queryWrapper.eq(AddressBook::getUserId, UserContext.currentUserId());
        return PageHelperUtils.selectPage(addressBookPageQueryReqDTO, () -> baseMapper.selectList(bookLambdaQueryWrapper));
    }

    /**
     * 修改地址簿
     *
     * @param id
     * @param dto
     * @author afei
     */
    @Override
    public void updateAddressBook(Long id, AddressBookUpsertReqDTO dto) {
        AddressBook addressBook = BeanUtils.toBeanIgnoreError(dto, AddressBook.class);
        if (ObjectUtil.isEmpty(addressBook)) {
            return;
        }
        if (BeanUtils.isNotEmpty(dto.getLocation())) {
            String[] split = dto.getLocation().split(",");
            addressBook.setLon(Double.valueOf(split[0]));
            addressBook.setLat(Double.valueOf(split[1]));
            addressBook.setUserId(UserContext.currentUserId());
        } else {
            addressBook.setLon(null);
            addressBook.setLat(null);
        }
        lambdaUpdate()
                .set(AddressBook::getIsDefault, 0)
                .eq(AddressBook::getUserId, UserContext.currentUser().getId())
                .eq(AddressBook::getIsDefault,1)
                .update();
        // 使用 set 方法设置要更新的字段
        LambdaUpdateWrapper<AddressBook> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(AddressBook::getId, id)
                .eq(AddressBook::getUserId, UserContext.currentUserId())
                .set(AddressBook::getName, addressBook.getName())
                .set(AddressBook::getPhone, addressBook.getPhone())
                .set(AddressBook::getProvince, addressBook.getProvince())
                .set(AddressBook::getCity, addressBook.getCity())
                .set(AddressBook::getCounty, addressBook.getCounty())
                .set(AddressBook::getAddress, addressBook.getAddress())
                .set(AddressBook::getIsDefault, addressBook.getIsDefault())
                .set(AddressBook::getLon, addressBook.getLon())
                .set(AddressBook::getLat, addressBook.getLat());
        update(updateWrapper);
    }

    @Override
    public void deleteBatch(ArrayList<String> ids) {
        for (String id : ids) {
            long addressId = Long.parseLong(id);
            addressBookMapper.deleteById(addressId);
            lambdaUpdate().set(AddressBook::getIsDeleted, 1)
                    .eq(AddressBook::getId, addressId).update();
        }
    }

    @Override
    public void updateDefaultAddress(Long id, Integer flag) {
        List<AddressBook> bookList = lambdaQuery()
                .eq(AddressBook::getUserId, UserContext.currentUser().getId())
                .eq(AddressBook::getIsDefault, 1).list();

        if (!bookList.isEmpty()) {
            // 将所有默认地址的标志设置为0
            lambdaUpdate()
                    .set(AddressBook::getIsDefault, 0)
                    .eq(AddressBook::getUserId, UserContext.currentUser().getId())
                    .eq(AddressBook::getIsDefault,1)
                    .update();
        }

        // 设置当前地址为默认地址
            lambdaUpdate()
                    .set(AddressBook::getIsDefault, flag)
                    .eq(AddressBook::getId, id)
                    .eq(AddressBook::getUserId, UserContext.currentUser().getId())
                    .update();
    }

    @Override
    public AddressBook getDefaultAddress() {
        List<AddressBook> bookList = lambdaQuery().eq(AddressBook::getUserId, UserContext.currentUserId())
                .eq(AddressBook::getIsDefault, 1).list();
        if (bookList.size()==1){
            return bookList.get(0);
        } else if (bookList.size()>1) {
            throw  new ForbiddenOperationException("只能有一个默认地址");
        }
        return null;
    }

}
